<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UploadsController extends Controller
{
    /**
     * 后台视频上传
     * @param Request $request
     * @return array|string
     */
    public function uploadImg(Request $request)
    {
        if ($request->isMethod('post')) {
//            dd($request->all());

            // 删除视频
            if ($request->input('key')) {
                if (file_exists('uploads/' . $request->input('key'))) {
                    unlink('uploads/' . $request->input('key'));
                }
                return ['status' => true];
            }

            $file = $request->file('_file_');
            $dirName = $request->input('type'); // 上传目标文件夹名称

            // 文件是否上传成功
            if ($file->isValid()) {

                // 获取文件相关信息
                $originalName = $file->getClientOriginalName(); // 文件原名
                $ext = $file->getClientOriginalExtension();     // 扩展名
//                $realPath = $file->getRealPath();   //临时文件的绝对路径
//                $type = $file->getClientMimeType();     // image/jpeg
                $fileSize = $file->getClientSize();     // 获得文件大小
                if ($fileSize > 1024 * 1024 * 100) {
                    return [
                        'status' => false,
                        'error' => [
                            'code' => 103,
                            'message' => '文件过大',
                        ]
                    ];
                }
                $arr = ['mp4'];
                if (!in_array($ext, $arr)) {
                    return [
                        'status' => false,
                        'error' => [
                            'code' => 103,
                            'message' => '文件类型错误',
                        ]
                    ];
                }

                $filename = date('YmdHis') . $originalName;
                if (empty($dirName)) {
                    $dirName = 'video';
                }
                $file->move('uploads/' . $dirName, $filename);

                $videoData = [
                    'status' => true,
                    'id' => $dirName.'/'.$filename,
                    'name' => $filename,
                    'path' => $filename,
                    'url' => config('app.img_url') . $dirName . '/' . $filename
                ];

                return $videoData;


            }

        }

    }
}
